//
//  WBComposeView.swift
//  Weibo
//
//  Created by xu on 2017/3/27.
//  Copyright © 2017年 xuantong. All rights reserved.
//

import UIKit
import pop

class WBComposeView: UIView {
    
    var target: UIViewController?

    override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //通过类来创建
    class func show(target: UIViewController){
        
        let composeView = WBComposeView()
        composeView.target = target
        target.view .addSubview(composeView)
        composeView.setupComposeButtonsAnim(isUp: true)
        
    }
    
    var composeButtons:[WBComposeButton] = [WBComposeButton]()
    //MARK: 设置视图
    private func setupUI() {
        addSubview(bgImageView)
        addSubview(sloganImageView)
        // 设置约束
        bgImageView.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        
        sloganImageView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        
        //按钮方法
       addComposeButtons()
    }
    
    //懒加载控件
    private lazy var bgImageView :UIImageView = {
        
        let img = UIImageView(image: UIImage.getScreenSnap()?.applyLightEffect())
        return img
    }()
    
    //广告图片
    private lazy var sloganImageView: UIImageView =  UIImageView(imgName: "compose_slogan")
    
    
    //添加按钮
    private func addComposeButtons() {
        
        let btnW:CGFloat = 80
        let btnH:CGFloat = 110
        let margin = (ScreenWidth - 3*80)/4
        
        let composeArray = loadComposeDate()
        
        for (i, composeModel) in composeArray.enumerated(){
            
            let btn = WBComposeButton()
            let colIndex = CGFloat(i%3)
            let rowIndex = CGFloat(i/3)
            
            btn.composeModel = composeModel
            
            let btnX = margin + (btnW+margin) * colIndex
           
            let btnY = rowIndex * (btnH + margin) + ScreenHeight
            
            btn.frame = CGRect(x: btnX, y:btnY, width: btnW, height: btnH)
            
            btn.setImage(UIImage (named:"tabbar_compose_friend"), for: .normal)
            btn.setTitle("@好友", for: .normal)
            btn.addTarget(self, action: #selector(buttonAction), for: UIControlEvents.touchUpInside)
            
            //赋值
            btn.setImage(UIImage(named:composeModel.icon ?? ""), for: UIControlState.normal)
            btn.setTitle(composeModel.title, for: UIControlState.normal)
           
            addSubview(btn)
            //添加到可变数组中
            composeButtons.append(btn)
            
        }
        
    }
    
    
    //加载plist文件
    fileprivate func loadComposeDate() ->[WBComposeModel] {
        
        let file = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        let plistArray = NSArray(contentsOfFile: file)!
        let  tempArray = NSArray.yy_modelArray(with: WBComposeModel.self, json:plistArray) as! [WBComposeModel]
        
        return tempArray
        
    }
    
}

//添加第三方pop动画效果
extension WBComposeView {
    func setupComposeButtonsAnim(isUp: Bool){
        let maxHeight: CGFloat = isUp == true ? -350 : 350
         let tempArray = isUp == true ? composeButtons : composeButtons.reversed()
         for (i,button) in tempArray.enumerated() {
          let anSpring = POPSpringAnimation(propertyNamed: kPOPViewCenter)!
          anSpring.toValue = CGPoint(x: button.center.x, y: button.center.y + maxHeight)
          anSpring.beginTime = CACurrentMediaTime()+Double(i)*0.025
          button.pop_add(anSpring, forKey: nil)
            
        }
    }
}


//按钮点击方法监听
extension WBComposeView {
    
    @objc fileprivate func buttonAction(button: WBComposeButton) {
       
        //按钮添加动画,实现选中的按钮进行放大效果
        UIView.animate(withDuration: 0.25, animations: {
            //遍历数组中的按钮
            for composeButton in self.composeButtons {
                composeButton.alpha = 0.2
                
                //判断当前点击的按钮
                if composeButton == button{
                    composeButton.transform = CGAffineTransform (scaleX: 2, y: 2)
                    
                }else{
                    composeButton.transform = CGAffineTransform (scaleX: 0.2, y: 0.2)
                }
                
            }
            
        },completion: { (_) in
            
            UIView.animate(withDuration: 0.25, animations: {
                for composeButton in self.composeButtons {
                    composeButton.alpha = 1
                    composeButton.transform = CGAffineTransform .identity
                }
                
            }, completion: { (_) in
                
                guard let className = button.composeModel?.classname else{
                    return
                }
                
                let classType = NSClassFromString(className) as! UIViewController.Type
               
                //实例化
                let vc = classType.init()
                
                self.target?.present(WBController(rootViewController: vc), animated: true, completion: {
                    
                    self.removeFromSuperview()
                })
                
                
                
            })
            
        })
        
    }
    
}

//当手机点击屏幕进行移除 视图
extension WBComposeView {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.setupComposeButtonsAnim(isUp: false)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.5) {
            self.removeFromSuperview()
        }
    
    }
}

